﻿using Codemonk.Pease.Common;
using System;
using System.Net;
using System.Text;

namespace Codemonk.Pease.Demo
{
    public class HttpCommunicator : ICommunicator<string>
    {
        private static void Request(string data, Uri url, Action<Exception> error, Action<string> back)
        {
            WebClient client = new WebClient();
            client.Encoding = Encoding.UTF8;
            client.Headers.Add("Accept", "*/*");
            client.Headers.Add("Accept-Language", "zh-CN");


            UploadStringCompletedEventHandler handler = null;
            handler = (s, e) =>
            {
                client.UploadStringCompleted -= handler;
                if (e.Error == null)
                {
                    if (back != null) back(e.Result);
                }
                else
                {
                    if (error != null) error(new Exception("访问服务器失败，请检查网络"));
                }
            };

            client.UploadStringCompleted += handler;
            try
            {
                client.UploadStringAsync(url, "POST", data);
            }
            catch (System.Exception ex)
            {
                if (error != null) error(ex);
            }
        }

        public void Request(string data, InterfaceServer server, Action<Exception> error, Action<string> back)
        {
            Request(data, new Uri(server.Address), error, back);
        }
    }
}
